import json
import os
from django.db import models

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.core.exceptions import ValidationError
from django import forms

# 获取项目根目录路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 读取 config.json 文件获取部门信息
config_path = os.path.join(BASE_DIR, 'PM', 'config.json')
with open(config_path, 'r') as config_file:
    config = json.load(config_file)
    DEPARTMENTS = [(dept, dept) for dept in config.get('DEPARTMENTS', [])]


class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=150, unique=True, verbose_name="用户名")
    engineer_id = models.CharField(max_length=50, unique=True, verbose_name="工程师ID")
    email = models.EmailField(max_length=255, unique=True, verbose_name="邮箱")
    department = models.CharField(max_length=100, blank=True, null=True, choices=DEPARTMENTS, verbose_name="部门")
    ROLE_CHOICES = [
        ('admin', 'Admin'),
        ('user', 'User'),
    ]
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='user')
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=True)

    objects = BaseUserManager()  # 使用默认的 BaseUserManager

    USERNAME_FIELD = 'email'

    # 添加 related_name 参数以避免与 auth.User 的字段冲突
    groups = models.ManyToManyField(
        'auth.Group',
        verbose_name='groups',
        blank=True,
        help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.',
        related_name="pm_user_groups",
        related_query_name="pm_user",
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        verbose_name='user permissions',
        blank=True,
        help_text='Specific permissions for this user.',
        related_name="pm_user_permissions",
        related_query_name="pm_user",
    )

    def clean(self):
        if self.role not in dict(self.ROLE_CHOICES).keys():
            raise ValidationError({'role': 'Invalid role'})
        if User.objects.filter(username=self.username).exists():
            raise ValidationError({'username': 'Username already exists'})

    def __str__(self):
        return self.username


class UserModelForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'engineer_id', 'email', 'password', 'department']  # 移除 role 字段
        widgets = {
            'password': forms.PasswordInput(),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    def clean(self):
        cleaned_data = super().clean()
        # 自定义验证逻辑
        if User.objects.filter(username=cleaned_data.get('username')).exists():
            raise ValidationError({'username': 'Username already exists'})
        return cleaned_data


class ReportData(models.Model):
    data = models.JSONField(verbose_name="表单数据")  # 将表单数据存储为JSON格式

    before_clean_images = models.TextField(verbose_name="清洁前图片")  # 移除upload_to参数
    after_clean_images = models.TextField(verbose_name="清洁后图片")  # 移除upload_to参数

    report_date = models.DateField(verbose_name="报告日期")  # 添加报告日期字段
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="创建用户", related_name='reports',
                                   null=True)  # 允许字段为空
    department = models.CharField(max_length=100, blank=True, null=True, verbose_name="部门")  # 新增部门字段，默认为空

    def __str__(self):
        return f"{self.data.get('customer_name', '')} - {self.report_date}"

    class Meta:
        verbose_name = "报告数据"
        verbose_name_plural = "报告数据"
